#include <iostream>  
#include <string>  
using namespace std;  
  
void computeLPSArray(string pattern, int lps[], int len) {  
    int len1 = 0;   
    lps[0] = 0;   
    
    int i = 1;  
    while (i < len) {  
        if (pattern[i] == pattern[len1]) {  
            len1++;  
            lps[i] = len1;  
            i++;  
        } else {  
            if (len1 != 0) {  
                len1 = lps[len1 - 1];  
            } else {  
                lps[i] = 0;  
                i++;  
            }  
        }  
    }  
}  
  
void KMPSearch(string pattern, string text) {  
    int m = pattern.length();  
    int n = text.length();  
    
    int lps[m];  
    computeLPSArray(pattern, lps, m);  
    
    int i = 0;   
    int j = 0;   
    
    while (i < n) {  
        if (pattern[j] == text[i]) {  
            i++;  
            j++;  
        }  
    
        if (j == m) {  
            cout << "Pattern found at index " << i - j << endl;  
            j = lps[j - 1];   
        } else if (i < n && pattern[j] != text[i]) {   
            if (j != 0) {   
                j = lps[j - 1];   
            } else {   
                i++;   
            }   
        }   
    }   
}   
    
int main() {   
    string pattern = "abc";   
    string text = "defabcghi";   
    KMPSearch(pattern, text);   
    return 0;   
}
